define(function(require, exports){
	var $		= require("jquery");
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');
	var utilDSP = require('modules/common');

	var List = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'P-sweety',
				'urlDelete': 'sweety/remove',
				'urlRecover': 'sweety/recover',
				'urlDisable': 'sweety/pause',
				'urlEnable': 'sweety/start',
				'urlDownload': '/api/dsp/download/sweety/',
				'vModel':{
					'view': {
						'addButton': pubjs.checkRight('sweety.add'),
						'verify': pubjs.checkRight('sweety.verify')
					},
					'vmClickAdd': this.eventClickAdd,
					'vmClickVerify': this.eventClickVerify
				}
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			this.append($([
				'<div class="M-formHead">',
					'<button v-show="view.addButton" class="btn btn-primary mr10" v-on:click="vmClickAdd">'+LANG('新建创意包')+'</button>',
					'<button v-show="view.verify" class="btn btn-primary mr10" v-on:click="vmClickVerify">'+LANG('查看审核结果')+'</button>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="sweety/grid/sweety.base"/>'
			].join('')));

			this.vm.mount();

			var c = this.getConfig();

			var config = {
				grid: {
					subs: ['creative', 'whisky', 'mediaAndAd', 'period', 'frequency', 'region', 'client', 'campaign', 'product'],
					hasMenu: true,
					hasBatch: true,
					hasSelect: true,
					hasSwitch: false,
					hasAmount: true,
					hasAutoRefresh: true,
					hasFilter: true,
					hasSearch: true,
					hasExport: pubjs.checkRight('sweety.export'),
					param: {
						AdvertiserId: +util.getQueryString('aderId'),
						PlanId: +util.getQueryString('planId'),
						CampaignId: +util.getQueryString('campaignId')
					}
				},
				date:{
					pos: 'bR'
				}
			};
			this.buildFromTemplate(config);

			// 创建弹框
			this.createAsync('popwin', '@base/dialog.base', {
				'size': 'xl'
			});

			this.createAsync('sidebar', '@layout/v1/sidebar.base', {
				'target': c.targetSidebar,
				'items': [
					// {'name': 'label', 'uri':'modules/sideBarBase.label', 'config': {
					// 	url: 'sweety/labels'
					// }},
					{'name': 'status', 'uri':'modules/sideBarBase.radio', 'config': {
						'title': LANG('状态：'),
						'data': [
							{id: 0, name: LANG('所有')},
							{id: -1, name: LANG('未归档')},
							{id: -2, name: LANG('已归档')},
							{id: 1, name: LANG('进行中')},
							{id: 2, name: LANG('已暂停')}
						],
						'value': 0
					}},
					{'name': 'metrics', 'uri':'modules/sideBarBase.metrics', 'config': {
						'metrics': ["{front}","{back}","{conversion}","{cost}"]
					}}
				]
			});
		},
		eventClickAdd: function(ev){
			var c = this.getConfig();
			pubjs.controller.navigate('serving/sweetyEdit' + utilDSP.getBrandSearch());
		},
		eventClickVerify: function(ev){
			var c = this.getConfig();
			pubjs.controller.navigate('serving/SweetyVerify' + utilDSP.getBrandSearch());
		},
		showSubgrid: function(id, title){
			if(!this.$ || (this.$ && !this.$.popwin)){
				return false;
			}
			var popwin = this.$.popwin;
			popwin.show();
			popwin.setTitle(title+'(ID:'+id+')'+LANG('-审核状态'));

			var mod = this.get('subgrid');
			if(!mod){
				var wrap = popwin.getContainer();
				var con = $('<div class="P-verifySweetySubgrid"/>').css({
					// width: 860,
					// height: 550
				}).appendTo(wrap);

				// 渠道
				var exchanger = pubjs.config('exchange');
				var metrics = [];
				util.each(exchanger, function(data){
					metrics.push({
						name: data.id,
						text: LANG(data.name),
						render: 'renderStatus',
						headerRender: 'renderHeader',
						align: 'center',
						param: data.alias_id || data.id
					});
				}, this);

				// 创建子表格
				mod = this.createAsync('subgrid', 'sweety/grid/verify.creative', {
					'target': con,
					'metrics': metrics,
					'hasRefresh': false,
					'param': {'SweetyId': +id},
					'wrapperClass': 'P-verifySweetySubgrid',
					'hasFilter': false
				});
			}else{
				mod.reload({
					'SweetyId': +id
				});
			}
		},
		reload: function(){
			this.$.grid.reload({
				AdvertiserId: +util.getQueryString('aderId'),
				PlanId: +util.getQueryString('planId'),
				CampaignId: +util.getQueryString('campaignId')
			});
		},
		onSidebarFilter: function(ev){
			var self = this
				,param = {};

			util.each(ev.param, function(item, idx){
				var type = idx
				var id = item.id;
				switch (type) {
					case 'label':
						param.Labels = id;
						break;
					case 'status':
						switch (+id){
							case 0:
							case 1:
							case 2:
								param.Status = +id;
								param.IsDeleted = 0;
								break;
							case -1:
								param.Status = 0;
								param.IsDeleted = 0;
								break;
							case -2:
								param.IsDeleted = 1;
								break;
						}
						break;
					case 'metrics':
						param.metrics_filter = id;
						break;
				}
			});
			self.$.grid.reload(param);
		},
		// 批量操作-下拉菜单界面
		onBatchShow: function(ev){
			var op = [];
			if (pubjs.checkRight('sweety.keyReplace'))
			{
				op.push({name: LANG('设置'), id: 'set', subs: [{name: LANG('创意包名称关键词替换'), id: 'keyReplace'}]});
			}
			if (pubjs.checkRight('sweety.pause'))
			{
				op.push({name: LANG('暂停'), id: 'disable'});
			}
			if (pubjs.checkRight('sweety.start'))
			{
				op.push({name: LANG('开始'), id: 'enable'});
			}
			if(pubjs.checkRight('sweety.remove')){
				op.push({name: LANG('归档'), id: 'delete'});
			}
			if(pubjs.checkRight('sweety.recover')){
				op.push({name: LANG('还原'), id: 'recover'});
			}
			if(pubjs.checkRight('sweety.download')){
				op.push({name: LANG('导出'), id: 'export'});
			}

			ev.returnValue = op;
			return false;
		},
		// 批量操作-响应菜单操作
		onBatchSelect: function(ev){
			var self = this;
			var data = ev.param[0];
			var ids = ev.param[1].join();
			if(!ids) {
				pubjs.alert(LANG('请先选择创意'));
				return false;
			}
			var c = this.getConfig();
			switch(data.key){
				case 'keyReplace':
					var pop = this.$ && this.$.replacePop;
					if(pop) {
						pop.setParam(ids).show();
					}
					else {
						this.createAsync('replacePop', 'sweety/popwin/batch.keyReplace', function(mod){
							mod.setParam(ids).show();
						});
					}
					break;
				case 'export':
					var url = utilDSP.getExportApi(this.get('grid'), ids);
					window.location.href = url;
					break;
				case 'delete':
					pubjs.confirm(LANG('确认删除以下创意包 %1 吗', ids), function(state) {
						if(state)
						{
							self.operateRequest(c.urlDelete, {'id': ids});
						}
					});
					break;
				case 'recover':
					self.operateRequest(c.urlRecover, {'id': ids});
					break;
				case 'disable':
					self.operateRequest(c.urlDisable, {'id': ids, Status: 2});
					break;
				case 'enable':
					self.operateRequest(c.urlEnable, {'id': ids, Status: 1});
					break;
			}
			//ev.from.hide();
			return false;
		},
		/*
			批量操作成功返回
		 */
		onBatchOperateSuccess: function(ev) {
			this.$.grid.reload();
			this.$.grid.setValue({selects: ev.param.ids});
		},
		// 操作菜单-下拉菜单界面
		onOperateMenuShow: function(ev){
			var row = ev.param;
			var op = [];
			ev.returnValue = op;

			if (row.IsDeleted && pubjs.checkRight('sweety.recover')){
				op.push({name: LANG('还原'), id: 'recover'});
			}
			else {
				switch (+row.Status)
				{
					case 1:
						if (pubjs.checkRight('sweety.pause'))
						{
							op.push({name: LANG("暂停"), id: 'disable'});
						}
						break;
					case 2:
						if (pubjs.checkRight('sweety.start'))
						{
							op.push({name: LANG("开启"), id: 'enable'});
						}
						break;
					default:
						break;
				}

				if(pubjs.checkRight('sweety.update'))
				{
					op.push({name: LANG('编辑'), id: 'edit'});
				}
				op.push(
					{name: LANG("创意审核"), id: 'verify'}
				);
				if(pubjs.checkRight('sweety.download')){
					// 只有本地上传的素材才有下载操作
					if (row.creativeType == 'upload')
					{
						op.push({name: LANG('下载'), id: 'download'});
					}
				}

				if(pubjs.checkRight('sweety.remove')){
					op.push({name: LANG('归档'), id: 'delete'});
				}
			}
			return false;
		},
		// 操作菜单-响应菜单操作
		onOperateMenuSelect: function(ev){
			var self = this;
			var op = ev.param[0]; // 按钮信息：{key: 1, name: '开始'}
			var data = ev.param[1];
			var c = this.getConfig();

			switch(op.key){
				case 'edit':

					pubjs.controller.navigate('serving/sweetyEdit/' + data._id + utilDSP.getBrandSearch());

					break;
				case 'verify':
					// pubjs.controller.navigate('sweety/verify/' + data._id );
					this.showSubgrid(data._id, data.Name);
					break;
				case 'download':
					window.open(c.urlDownload + data._id );
					break;
				case 'delete':
					pubjs.confirm(LANG('确认删除创意包 %1 吗', data._id), function(state) {
						if(state)
						{
							self.operateRequest(c.urlDelete, {id: +data._id});
						}
					});
					break;
				case 'recover':
					self.operateRequest(c.urlRecover, {id: +data._id});
					break;
				case 'disable':
					self.operateRequest(c.urlDisable, {id: +data._id});
					break;
				case 'enable':
					self.operateRequest(c.urlEnable, {id: +data._id});
					break;
			}
			return false;
		},
		operateRequest : function(url, param){
			var self = this;
			pubjs.loading.show();
			pubjs.mc.send(url, param, function(err, data){
				pubjs.loading.hide();
				if(err)
				{
					pubjs.alert(err.message);
					return false;
				}

				pubjs.alert(LANG('操作成功'));
				self.$.grid.setSelectRowIds([]).reload();
				return false;
			});
		},
		onSaveSweetySuccess: function(ev)
		{
			this.reload();

			if (ev.param && ev.param.id)
			{
				this.$.grid.setRowHighlight(ev.param.id);
			}
		}
	});
	exports.base = List;

});